package GUI;

import util.User;
import util.TravelRecord;
import util.TravelRecordDAO;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import javax.swing.Timer;

/**
 * 出行导航面板，用于提供绿色出行路线规划和导航服务
 */
public class TravelNavigationPanel extends JPanel {
    private User currentUser;
    private JTextField startLocationField;
    private JTextField endLocationField;
    private JComboBox<String> transportTypeComboBox;
    private JButton searchButton;
    private JPanel resultPanel;
    private JLabel statusLabel;

    // 地图选点相关变量
    private JTable mapTable;
    private String selectingFor = ""; // "start" 或 "end"
    private static final int MAP_ROWS = 15;
    private static final int MAP_COLS = 15;
    private Point startPoint = null;
    private Point endPoint = null;
    private Map<Point, String> mapLocations = new HashMap<>();

    // 路径规划和导航相关变量
    private List<Point> currentRoute = new ArrayList<>();
    private Timer navigationTimer;
    private Point currentPosition;
    private int currentStepIndex = 0;
    private String currentTransportType;
    private double routeDistance;
    private int routeDuration;
    private double carbonReduction;
    private int earnedPoints;

    // 模拟的热门地点
    private String[] popularLocations = {
            "北京站", "北京西站", "北京南站", "北京北站", "首都机场",
            "北京大学", "清华大学", "中关村", "天安门广场", "鸟巢",
            "水立方", "颐和园", "圆明园", "天坛", "故宫"
    };

    public TravelNavigationPanel(User user) {
        this.currentUser = user;

        // 设置布局
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题面板
        JPanel titlePanel = new JPanel(new BorderLayout());
        titlePanel.setOpaque(false);

        JLabel titleLabel = new JLabel("绿色出行导航", JLabel.LEFT);
        titleLabel.setFont(new Font("等线", Font.BOLD, 20));
        titleLabel.setForeground(new Color(0, 120, 0));
        titlePanel.add(titleLabel, BorderLayout.WEST);

        // 添加标题面板到主面板
        add(titlePanel, BorderLayout.NORTH);

        // 创建中央面板，分为左右两部分
        JPanel centralPanel = new JPanel(new BorderLayout(15, 0));

        // 创建搜索面板（放在左侧）
        JPanel searchPanel = createSearchPanel();
        centralPanel.add(searchPanel, BorderLayout.WEST);

        // 创建地图面板（放在右侧）
        JPanel mapPanel = createMapPanel();
        centralPanel.add(mapPanel, BorderLayout.CENTER);

        // 添加中央面板
        add(centralPanel, BorderLayout.CENTER);

        // 删除下方标签提示，不再需要resultPanel
        resultPanel = new JPanel();
        resultPanel.setLayout(new BorderLayout());
        resultPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));
        add(resultPanel, BorderLayout.SOUTH);

        // 初始化地图上的地点
        initializeMapLocations();
    }

    /**
     * 初始化地图上的位置点
     */
    private void initializeMapLocations() {
        // 在地图上添加一些地点
        mapLocations.put(new Point(2, 3), "北京站");
        mapLocations.put(new Point(1, 8), "北京西站");
        mapLocations.put(new Point(10, 5), "北京南站");
        mapLocations.put(new Point(8, 1), "北京北站");
        mapLocations.put(new Point(11, 10), "首都机场");
        mapLocations.put(new Point(4, 6), "北京大学");
        mapLocations.put(new Point(5, 5), "清华大学");
        mapLocations.put(new Point(7, 7), "中关村");
        mapLocations.put(new Point(6, 10), "天安门广场");
        mapLocations.put(new Point(9, 8), "鸟巢");
        mapLocations.put(new Point(8, 9), "水立方");
        mapLocations.put(new Point(3, 9), "颐和园");
        mapLocations.put(new Point(2, 10), "圆明园");
        mapLocations.put(new Point(7, 3), "天坛");
        mapLocations.put(new Point(6, 8), "故宫");
    }

    /**
     * 创建搜索面板
     */
    private JPanel createSearchPanel() {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(220, 220, 220), 1),
                BorderFactory.createEmptyBorder(20, 20, 20, 20)));
        panel.setPreferredSize(new Dimension(320, 450));

        // 创建搜索表单
        JPanel formPanel = new JPanel(new GridBagLayout());
        formPanel.setOpaque(false);
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);

        // 起点
        JLabel startLabel = new JLabel("起点位置:");
        startLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        formPanel.add(startLabel, gbc);

        startLocationField = new JTextField(15);
        startLocationField.putClientProperty("JTextField.placeholderText", "输入起点位置");
        startLocationField.setPreferredSize(new Dimension(150, 30));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 1.0;
        formPanel.add(startLocationField, gbc);

        JButton selectStartButton = new JButton("选择");
        selectStartButton.addActionListener(e -> {
            selectingFor = "start";
            JOptionPane.showMessageDialog(this, "请在右侧地图上点击选择起点位置", "选择起点", JOptionPane.INFORMATION_MESSAGE);
        });
        gbc.gridx = 2;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.weightx = 0.0;
        formPanel.add(selectStartButton, gbc);

        // 终点
        JLabel endLabel = new JLabel("终点位置:");
        endLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(endLabel, gbc);

        endLocationField = new JTextField(15);
        endLocationField.putClientProperty("JTextField.placeholderText", "输入终点位置");
        endLocationField.setPreferredSize(new Dimension(150, 30));
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.weightx = 1.0;
        formPanel.add(endLocationField, gbc);

        JButton selectEndButton = new JButton("选择");
        selectEndButton.addActionListener(e -> {
            selectingFor = "end";
            JOptionPane.showMessageDialog(this, "请在右侧地图上点击选择终点位置", "选择终点", JOptionPane.INFORMATION_MESSAGE);
        });
        gbc.gridx = 2;
        gbc.gridy = 1;
        gbc.weightx = 0.0;
        formPanel.add(selectEndButton, gbc);

        // 交通方式
        JLabel typeLabel = new JLabel("交通方式:");
        typeLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(typeLabel, gbc);

        String[] transportTypes = { "公交优先", "地铁优先", "骑行优先", "步行优先", "推荐路线" };
        transportTypeComboBox = new JComboBox<>(transportTypes);
        transportTypeComboBox.setPreferredSize(new Dimension(150, 30));
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.gridwidth = 2;
        formPanel.add(transportTypeComboBox, gbc);

        // 搜索按钮
        searchButton = new JButton("规划路线");
        searchButton.setBackground(new Color(0, 120, 0));
        searchButton.setForeground(Color.WHITE);
        searchButton.setFont(new Font("等线", Font.BOLD, 14));
        searchButton.setPreferredSize(new Dimension(150, 35));
        searchButton.addActionListener(e -> searchRoute());
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 3;
        gbc.insets = new Insets(15, 5, 5, 5);
        formPanel.add(searchButton, gbc);

        // 设置面板最大宽度
        Dimension formSize = new Dimension(280, formPanel.getPreferredSize().height);
        formPanel.setPreferredSize(formSize);
        formPanel.setMaximumSize(formSize);
        panel.add(formPanel);

        // 添加热门目的地面板
        JPanel popularPanel = createPopularLocationsPanel();
        panel.add(Box.createVerticalStrut(20));
        panel.add(popularPanel);

        return panel;
    }

    /**
     * 创建地图面板
     */
    private JPanel createMapPanel() {
        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createTitledBorder(
                BorderFactory.createLineBorder(new Color(200, 200, 200), 1),
                "地图选点",
                TitledBorder.LEFT,
                TitledBorder.TOP,
                new Font("等线", Font.BOLD, 14)));
        panel.setPreferredSize(new Dimension(540, 450));

        // 创建地图表格模型
        DefaultTableModel model = new DefaultTableModel(MAP_ROWS, MAP_COLS) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        // 创建地图表格
        mapTable = new JTable(model);
        mapTable.setRowHeight(30);
        mapTable.setShowGrid(true);
        mapTable.setGridColor(new Color(230, 230, 230));
        mapTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        mapTable.setTableHeader(null); // 隐藏表头

        // 设置列宽
        for (int i = 0; i < mapTable.getColumnCount(); i++) {
            mapTable.getColumnModel().getColumn(i).setMinWidth(30);
            mapTable.getColumnModel().getColumn(i).setMaxWidth(30);
            mapTable.getColumnModel().getColumn(i).setPreferredWidth(30);
        }

        // 自定义单元格渲染器
        mapTable.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel label = (JLabel) super.getTableCellRendererComponent(
                        table, "", isSelected, hasFocus, row, column);
                label.setHorizontalAlignment(JLabel.CENTER);

                Point currentPoint = new Point(row, column);

                // 设置背景色
                if (startPoint != null && startPoint.equals(currentPoint)) {
                    // 起点标记
                    label.setBackground(new Color(231, 76, 60));
                    label.setForeground(Color.WHITE);
                    label.setText("起");
                } else if (endPoint != null && endPoint.equals(currentPoint)) {
                    // 终点标记
                    label.setBackground(new Color(52, 152, 219));
                    label.setForeground(Color.WHITE);
                    label.setText("终");
                } else if (currentPosition != null && currentPosition.equals(currentPoint)) {
                    // 当前位置标记（导航时）
                    label.setBackground(new Color(155, 89, 182));
                    label.setForeground(Color.WHITE);
                    label.setText("我");
                } else if (currentRoute.contains(currentPoint) && !currentPoint.equals(startPoint)
                        && !currentPoint.equals(endPoint)) {
                    // 路线标记
                    if (currentTransportType != null) {
                        switch (currentTransportType) {
                            case "公交优先":
                                label.setBackground(new Color(46, 204, 113));
                                break;
                            case "地铁优先":
                                label.setBackground(new Color(52, 152, 219));
                                break;
                            case "骑行优先":
                                label.setBackground(new Color(230, 126, 34));
                                break;
                            case "步行优先":
                                label.setBackground(new Color(155, 89, 182));
                                break;
                            default:
                                label.setBackground(new Color(0, 120, 0));
                                break;
                        }
                        label.setForeground(Color.WHITE);
                        label.setText("·");
                    }
                } else if (mapLocations.containsKey(currentPoint)) {
                    // 热门位置标记
                    label.setBackground(new Color(46, 204, 113));
                    label.setForeground(Color.WHITE);
                    label.setText("地");
                    // 设置工具提示
                    label.setToolTipText(mapLocations.get(currentPoint));
                } else {
                    // 普通单元格
                    label.setBackground(Color.WHITE);
                    label.setText("");
                }

                return label;
            }
        });

        // 地图点击事件
        mapTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = mapTable.rowAtPoint(e.getPoint());
                int column = mapTable.columnAtPoint(e.getPoint());

                Point clickedPoint = new Point(row, column);
                String locationName = mapLocations.containsKey(clickedPoint) ? mapLocations.get(clickedPoint) : "自定义位置";

                if (selectingFor.equals("start")) {
                    startPoint = clickedPoint;
                    startLocationField.setText(locationName);
                    selectingFor = ""; // 重置选择状态
                } else if (selectingFor.equals("end")) {
                    endPoint = clickedPoint;
                    endLocationField.setText(locationName);
                    selectingFor = ""; // 重置选择状态
                } else {
                    // 显示位置信息
                    if (mapLocations.containsKey(clickedPoint)) {
                        JOptionPane.showMessageDialog(TravelNavigationPanel.this,
                                "您点击了: " + mapLocations.get(clickedPoint),
                                "位置信息", JOptionPane.INFORMATION_MESSAGE);
                    }
                }

                // 刷新地图显示
                mapTable.repaint();
            }
        });

        // 添加地图说明
        JPanel legendPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));

        JLabel startLegend = new JLabel(" 起 ");
        startLegend.setOpaque(true);
        startLegend.setBackground(new Color(231, 76, 60));
        startLegend.setForeground(Color.WHITE);
        startLegend.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JLabel endLegend = new JLabel(" 终 ");
        endLegend.setOpaque(true);
        endLegend.setBackground(new Color(52, 152, 219));
        endLegend.setForeground(Color.WHITE);
        endLegend.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JLabel userLegend = new JLabel(" 我 ");
        userLegend.setOpaque(true);
        userLegend.setBackground(new Color(155, 89, 182));
        userLegend.setForeground(Color.WHITE);
        userLegend.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        JLabel locationLegend = new JLabel(" 地 ");
        locationLegend.setOpaque(true);
        locationLegend.setBackground(new Color(46, 204, 113));
        locationLegend.setForeground(Color.WHITE);
        locationLegend.setBorder(BorderFactory.createLineBorder(Color.BLACK));

        legendPanel.add(startLegend);
        legendPanel.add(new JLabel(" - 起点"));
        legendPanel.add(Box.createHorizontalStrut(10));
        legendPanel.add(endLegend);
        legendPanel.add(new JLabel(" - 终点"));
        legendPanel.add(Box.createHorizontalStrut(10));
        legendPanel.add(userLegend);
        legendPanel.add(new JLabel(" - 当前位置"));
        legendPanel.add(Box.createHorizontalStrut(10));
        legendPanel.add(locationLegend);
        legendPanel.add(new JLabel(" - 地点"));

        // 添加地图标题
        JLabel mapTitleLabel = new JLabel(" 北京地区地图", JLabel.CENTER);
        mapTitleLabel.setFont(new Font("等线", Font.BOLD, 16));
        mapTitleLabel.setForeground(new Color(70, 70, 70));

        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.add(mapTitleLabel, BorderLayout.CENTER);

        // 组装面板
        panel.add(headerPanel, BorderLayout.NORTH);
        panel.add(new JScrollPane(mapTable), BorderLayout.CENTER);
        panel.add(legendPanel, BorderLayout.SOUTH);

        return panel;
    }

    /**
     * 搜索路线
     */
    private void searchRoute() {
        String startLocation = startLocationField.getText().trim();
        String endLocation = endLocationField.getText().trim();
        String transportType = (String) transportTypeComboBox.getSelectedItem();

        if (startLocation.isEmpty() || endLocation.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请填写起点和终点位置", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        if (startPoint == null || endPoint == null) {
            JOptionPane.showMessageDialog(this, "请在地图上选择起点和终点", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 使用A*算法规划路线
        currentRoute = findPath(startPoint, endPoint, transportType);

        if (currentRoute.isEmpty()) {
            JOptionPane.showMessageDialog(this, "无法找到从" + startLocation + "到" + endLocation + "的路线，请重新选择",
                    "路线规划失败", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 计算路线统计数据
        calculatedRouteStats(transportType);

        // 刷新地图以显示路线
        currentTransportType = transportType;
        mapTable.repaint();

        // 显示路线结果（在热门目的地下方）
        displayRouteResultInPanel(startLocation, endLocation, transportType);
    }

    /**
     * 在搜索面板中显示路线结果
     */
    private void displayRouteResultInPanel(String startLocation, String endLocation, String transportType) {
        // 获取搜索面板（即左侧面板的第一个子组件）
        JPanel searchPanel = (JPanel) ((BorderLayout) getLayout()).getLayoutComponent(BorderLayout.CENTER);
        JPanel leftPanel = (JPanel) ((BorderLayout) searchPanel.getLayout()).getLayoutComponent(BorderLayout.WEST);

        // 移除旧的路线结果组件（如果存在）
        Component[] components = leftPanel.getComponents();
        for (int i = 0; i < components.length; i++) {
            if (components[i] instanceof JPanel && components[i].getName() != null
                    && components[i].getName().equals("routeResultPanel")) {
                leftPanel.remove(components[i]);
                break;
            }
        }

        // 创建路线结果面板
        JPanel routeResultPanel = new JPanel(new BorderLayout(0, 10));
        routeResultPanel.setName("routeResultPanel");
        routeResultPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(220, 220, 220)),
                BorderFactory.createEmptyBorder(10, 0, 0, 0)));

        // 添加标题
        JLabel titleLabel = new JLabel("路线详情", JLabel.LEFT);
        titleLabel.setFont(new Font("等线", Font.BOLD, 16));
        routeResultPanel.add(titleLabel, BorderLayout.NORTH);

        // 添加路线概要信息
        JPanel summaryPanel = new JPanel(new GridLayout(2, 2, 5, 5));
        summaryPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));

        JLabel distanceLabel = new JLabel("距离: " + String.format("%.1f", routeDistance) + " 公里");
        distanceLabel.setFont(new Font("等线", Font.BOLD, 13));
        summaryPanel.add(distanceLabel);

        JLabel durationLabel = new JLabel("时间: 约" + routeDuration + " 分钟");
        durationLabel.setFont(new Font("等线", Font.BOLD, 13));
        summaryPanel.add(durationLabel);

        JLabel carbonLabel = new JLabel("减碳: " + String.format("%.2f", carbonReduction) + " 千克");
        carbonLabel.setFont(new Font("等线", Font.BOLD, 13));
        carbonLabel.setForeground(new Color(0, 150, 0));
        summaryPanel.add(carbonLabel);

        JLabel pointsLabel = new JLabel("预计积分: +" + earnedPoints);
        pointsLabel.setFont(new Font("等线", Font.BOLD, 13));
        pointsLabel.setForeground(new Color(0, 150, 0));
        summaryPanel.add(pointsLabel);

        // 添加详细信息（简化版本）
        List<String> steps = generateRouteSteps(startLocation, endLocation, transportType);
        JPanel stepsPanel = new JPanel();
        stepsPanel.setLayout(new BoxLayout(stepsPanel, BoxLayout.Y_AXIS));
        stepsPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        for (String step : steps) {
            JLabel stepLabel = new JLabel(step);
            stepLabel.setFont(new Font("等线", Font.PLAIN, 12));
            stepLabel.setBorder(BorderFactory.createEmptyBorder(3, 0, 3, 0));
            JPanel stepRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
            stepRow.add(stepLabel);
            stepsPanel.add(stepRow);
        }

        JScrollPane stepsScrollPane = new JScrollPane(stepsPanel);
        stepsScrollPane.setPreferredSize(new Dimension(280, 150));
        stepsScrollPane.setBorder(BorderFactory.createEmptyBorder());

        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.add(summaryPanel, BorderLayout.NORTH);
        contentPanel.add(stepsScrollPane, BorderLayout.CENTER);

        // 添加操作按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        JButton startNavButton = new JButton("开始导航");
        startNavButton.setBackground(new Color(0, 120, 0));
        startNavButton.setForeground(Color.WHITE);
        startNavButton.setFont(new Font("等线", Font.BOLD, 14));
        startNavButton.addActionListener(e -> startNavigation(startLocation, endLocation, transportType));
        buttonPanel.add(startNavButton);

        routeResultPanel.add(contentPanel, BorderLayout.CENTER);
        routeResultPanel.add(buttonPanel, BorderLayout.SOUTH);

        // 将路线结果面板添加到左侧面板
        leftPanel.add(Box.createVerticalStrut(20));
        leftPanel.add(routeResultPanel);

        // 刷新UI
        leftPanel.revalidate();
        leftPanel.repaint();

        // 清除原有的下方结果面板
        resultPanel.removeAll();
        resultPanel.revalidate();
        resultPanel.repaint();
    }

    /**
     * 计算路线统计数据
     */
    private void calculatedRouteStats(String transportType) {
        // 计算路线距离（每格按照0.5公里计算）
        routeDistance = (currentRoute.size() - 1) * 0.5;

        // 计算时间（按照不同交通方式的平均速度）
        switch (transportType) {
            case "公交优先":
                routeDuration = (int) (routeDistance / 0.5 * 6); // 约6分钟/0.5公里
                break;
            case "地铁优先":
                routeDuration = (int) (routeDistance / 0.5 * 4); // 约4分钟/0.5公里
                break;
            case "骑行优先":
                routeDuration = (int) (routeDistance / 0.5 * 8); // 约8分钟/0.5公里
                break;
            case "步行优先":
                routeDuration = (int) (routeDistance / 0.5 * 15); // 约15分钟/0.5公里
                break;
            default:
                routeDuration = (int) (routeDistance / 0.5 * 6); // 默认
                break;
        }

        // 计算积分和碳减排
        String travelType = "";
        switch (transportType) {
            case "公交优先":
                travelType = "公交";
                break;
            case "地铁优先":
                travelType = "地铁";
                break;
            case "骑行优先":
                travelType = "共享单车";
                break;
            case "步行优先":
                travelType = "步行";
                break;
            default:
                travelType = "公交";
                break;
        }

        earnedPoints = calculatePoints(travelType, routeDistance);
        carbonReduction = calculateCarbonReduction(travelType, routeDistance);
    }

    /**
     * 生成模拟的路线步骤
     */
    private List<String> generateRouteSteps(String startLocation, String endLocation, String transportType) {
        List<String> steps = new ArrayList<>();

        if (transportType.equals("推荐路线") || transportType.equals("公交优先")) {
            steps.add("1. 从 " + startLocation + " 步行约200米至最近公交站");
            steps.add("2. 乘坐 42路公交车，行驶约4站");
            steps.add("3. 在 中关村站 下车，步行约100米至地铁站");
            steps.add("4. 乘坐 4号线地铁，行驶约3站");
            steps.add("5. 在 西直门站 下车，步行约300米到达 " + endLocation);
        } else if (transportType.equals("地铁优先")) {
            steps.add("1. 从 " + startLocation + " 步行约300米至最近地铁站");
            steps.add("2. 乘坐 10号线地铁，行驶约5站");
            steps.add("3. 在 国贸站 换乘 1号线，行驶约2站");
            steps.add("4. 在 永安里站 下车，步行约400米到达 " + endLocation);
        } else if (transportType.equals("骑行优先")) {
            steps.add("1. 从 " + startLocation + " 步行约100米至共享单车站点");
            steps.add("2. 骑行共享单车，沿主干道行驶约3.5公里");
            steps.add("3. 在 " + endLocation + " 附近的单车站点停车，步行约50米到达目的地");
        } else if (transportType.equals("步行优先")) {
            steps.add("1. 从 " + startLocation + " 出发，沿主干道步行");
            steps.add("2. 经过市政公园，继续向东步行约1公里");
            steps.add("3. 穿过步行街，继续向南步行约500米到达 " + endLocation);
        }

        return steps;
    }

    /**
     * 创建热门目的地面板
     */
    private JPanel createPopularLocationsPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setOpaque(false);

        JLabel titleLabel = new JLabel("热门目的地", JLabel.LEFT);
        titleLabel.setFont(new Font("等线", Font.BOLD, 16));
        panel.add(titleLabel, BorderLayout.NORTH);

        JPanel locationsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 10, 10));
        locationsPanel.setOpaque(false);

        for (String location : popularLocations) {
            JButton locationButton = new JButton(location);
            locationButton.setFont(new Font("等线", Font.PLAIN, 12));
            locationButton.setFocusPainted(false);
            locationButton.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(new Color(200, 200, 200), 1, true),
                    BorderFactory.createEmptyBorder(5, 10, 5, 10)));
            locationButton.setBackground(new Color(245, 245, 245));
            locationButton.addActionListener(e -> endLocationField.setText(location));
            locationsPanel.add(locationButton);
        }

        panel.add(locationsPanel, BorderLayout.CENTER);
        return panel;
    }

    /**
     * 计算两点间的曼哈顿距离
     */
    private int manhattanDistance(Point p1, Point p2) {
        return Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y);
    }

    /**
     * 启动导航功能
     */
    private void startNavigation(String startLocation, String endLocation, String transportType) {
        if (currentRoute.isEmpty()) {
            JOptionPane.showMessageDialog(this, "没有可用的路线，请重新规划", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 停止已有的导航（如果有）
        stopNavigation();

        // 设置当前位置为起点
        currentPosition = new Point(startPoint.x, startPoint.y);
        currentStepIndex = 0;

        // 创建定时器，每秒移动一格
        navigationTimer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 导航过程中更新位置
                if (currentStepIndex < currentRoute.size()) {
                    currentPosition = currentRoute.get(currentStepIndex);
                    currentStepIndex++;
                    mapTable.repaint();
                } else {
                    // 导航结束
                    stopNavigation();

                    // 显示导航完成提示
                    JOptionPane.showMessageDialog(TravelNavigationPanel.this,
                            "导航已结束，出行成功！",
                            "导航完成", JOptionPane.INFORMATION_MESSAGE);

                    // 打开添加出行记录对话框
                    showAddTravelRecordDialog(startLocation, endLocation, transportType, routeDistance);
                }
            }
        });

        navigationTimer.start();
    }

    /**
     * 停止导航
     */
    private void stopNavigation() {
        if (navigationTimer != null && navigationTimer.isRunning()) {
            navigationTimer.stop();
        }
    }

    /**
     * 使用A*算法规划路线
     */
    private List<Point> findPath(Point start, Point end, String transportType) {
        // 初始化路径列表
        List<Point> path = new ArrayList<>();

        // 如果起点和终点是同一点，直接返回包含该点的路径
        if (start.equals(end)) {
            path.add(new Point(start));
            return path;
        }

        // 使用简化版A*算法寻路
        List<PathNode> openList = new ArrayList<>();
        List<PathNode> closedList = new ArrayList<>();
        Map<Point, PathNode> pointNodeMap = new HashMap<>();

        // 添加起点到开放列表
        PathNode startNode = new PathNode(start, null, 0, manhattanDistance(start, end));
        openList.add(startNode);
        pointNodeMap.put(start, startNode);

        while (!openList.isEmpty()) {
            // 获取f值最小的节点
            PathNode current = openList.get(0);
            for (int i = 1; i < openList.size(); i++) {
                if (openList.get(i).f < current.f) {
                    current = openList.get(i);
                }
            }

            // 如果当前节点是终点，构建路径并返回
            if (current.point.equals(end)) {
                // 从终点回溯构建路径
                PathNode node = current;
                while (node != null) {
                    path.add(0, node.point);
                    node = node.parent;
                }
                return path;
            }

            // 将当前节点从开放列表移到关闭列表
            openList.remove(current);
            closedList.add(current);

            // 检查相邻节点
            int[][] directions = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; // 上下左右四个方向

            for (int[] dir : directions) {
                Point neighbor = new Point(current.point.x + dir[0], current.point.y + dir[1]);

                // 检查是否超出地图边界
                if (neighbor.x < 0 || neighbor.x >= MAP_ROWS || neighbor.y < 0 || neighbor.y >= MAP_COLS) {
                    continue;
                }

                // 如果节点已在关闭列表中，跳过
                boolean inClosedList = false;
                for (PathNode node : closedList) {
                    if (node.point.equals(neighbor)) {
                        inClosedList = true;
                        break;
                    }
                }
                if (inClosedList)
                    continue;

                // 计算从起点经过当前节点到相邻节点的代价
                int gCost = current.g + 1; // 相邻格子距离为1

                // 查找相邻节点是否已在开放列表中
                PathNode neighborNode = pointNodeMap.get(neighbor);

                if (neighborNode == null) {
                    // 如果节点不在开放列表中，添加它
                    neighborNode = new PathNode(neighbor, current, gCost, manhattanDistance(neighbor, end));
                    openList.add(neighborNode);
                    pointNodeMap.put(neighbor, neighborNode);
                } else if (gCost < neighborNode.g) {
                    // 如果找到更优路径，更新节点
                    neighborNode.parent = current;
                    neighborNode.g = gCost;
                    neighborNode.f = gCost + neighborNode.h;
                }
            }
        }

        // 如果无法找到路径，返回空列表
        return path;
    }

    /**
     * 路径节点内部类，用于A*算法
     */
    private class PathNode {
        Point point;
        PathNode parent;
        int g; // 从起点到当前节点的代价
        int h; // 从当前节点到终点的估计代价
        int f; // f = g + h

        public PathNode(Point point, PathNode parent, int g, int h) {
            this.point = point;
            this.parent = parent;
            this.g = g;
            this.h = h;
            this.f = g + h;
        }
    }

    /**
     * 显示添加出行记录对话框
     */
    private void showAddTravelRecordDialog(String startLocation, String endLocation, String transportType,
            double distance) {
        // 确定出行类型
        String travelType;
        switch (transportType) {
            case "公交优先":
                travelType = "公交";
                break;
            case "地铁优先":
                travelType = "地铁";
                break;
            case "骑行优先":
                travelType = "共享单车";
                break;
            case "步行优先":
                travelType = "步行";
                break;
            default:
                travelType = "公交";
                break;
        }

        // 创建对话框
        JDialog dialog = new JDialog((Frame) SwingUtilities.getWindowAncestor(this), "添加出行记录", true);
        dialog.setSize(500, 500);
        dialog.setLocationRelativeTo(this);
        dialog.setResizable(false);

        // 创建内容面板
        JPanel contentPanel = new JPanel(new BorderLayout(10, 10));
        contentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 创建标题
        JLabel titleLabel = new JLabel("添加绿色出行记录", JLabel.CENTER);
        titleLabel.setFont(new Font("等线", Font.BOLD, 18));
        titleLabel.setForeground(new Color(0, 120, 0));
        titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 20, 0));
        contentPanel.add(titleLabel, BorderLayout.NORTH);

        // 创建表单面板
        JPanel formPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.weightx = 1.0;
        gbc.gridwidth = 2;

        // 日期选择器
        JLabel dateLabel = new JLabel("出行日期:");
        dateLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        formPanel.add(dateLabel, gbc);

        // 创建日期选择器
        SpinnerDateModel dateModel = new SpinnerDateModel();
        dateModel.setValue(new Date()); // 默认为当前日期
        JSpinner dateSpinner = new JSpinner(dateModel);
        JSpinner.DateEditor dateEditor = new JSpinner.DateEditor(dateSpinner, "yyyy-MM-dd HH:mm");
        dateSpinner.setEditor(dateEditor);
        dateSpinner.setFont(new Font("等线", Font.PLAIN, 14));

        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        formPanel.add(dateSpinner, gbc);

        // 出行方式
        JLabel typeLabel = new JLabel("出行方式:");
        typeLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 1;
        formPanel.add(typeLabel, gbc);

        String[] travelTypes = { "公交", "地铁", "共享单车", "自行车", "步行" };
        JComboBox<String> travelTypeComboBox = new JComboBox<>(travelTypes);
        travelTypeComboBox.setFont(new Font("等线", Font.PLAIN, 14));
        travelTypeComboBox.setSelectedItem(travelType);

        gbc.gridx = 1;
        gbc.gridy = 1;
        formPanel.add(travelTypeComboBox, gbc);

        // 起点
        JLabel startLabel = new JLabel("起点位置:");
        startLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 2;
        formPanel.add(startLabel, gbc);

        JTextField startLocationField = new JTextField(startLocation);
        startLocationField.setFont(new Font("等线", Font.PLAIN, 14));
        startLocationField.setEditable(false);

        gbc.gridx = 1;
        gbc.gridy = 2;
        formPanel.add(startLocationField, gbc);

        // 终点
        JLabel endLabel = new JLabel("终点位置:");
        endLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 3;
        formPanel.add(endLabel, gbc);

        JTextField endLocationField = new JTextField(endLocation);
        endLocationField.setFont(new Font("等线", Font.PLAIN, 14));
        endLocationField.setEditable(false);

        gbc.gridx = 1;
        gbc.gridy = 3;
        formPanel.add(endLocationField, gbc);

        // 距离
        JLabel distanceLabel = new JLabel("出行距离(km):");
        distanceLabel.setFont(new Font("等线", Font.BOLD, 14));
        gbc.gridx = 0;
        gbc.gridy = 4;
        formPanel.add(distanceLabel, gbc);

        JTextField distanceField = new JTextField(String.format("%.1f", distance));
        distanceField.setFont(new Font("等线", Font.PLAIN, 14));
        distanceField.setEditable(false);

        gbc.gridx = 1;
        gbc.gridy = 4;
        formPanel.add(distanceField, gbc);

        // 积分预览
        JLabel pointsPreviewLabel = new JLabel("预计获得积分: " + earnedPoints);
        pointsPreviewLabel.setFont(new Font("等线", Font.BOLD, 14));
        pointsPreviewLabel.setForeground(new Color(0, 120, 0));
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        formPanel.add(pointsPreviewLabel, gbc);

        // 碳减排预览
        JLabel carbonPreviewLabel = new JLabel("预计碳减排: " + String.format("%.2f", carbonReduction) + " kg");
        carbonPreviewLabel.setFont(new Font("等线", Font.BOLD, 14));
        carbonPreviewLabel.setForeground(new Color(0, 120, 0));
        gbc.gridx = 0;
        gbc.gridy = 6;
        formPanel.add(carbonPreviewLabel, gbc);

        // 计算预览
        ActionListener previewCalculator = e -> {
            String currentTravelType = (String) travelTypeComboBox.getSelectedItem();
            double currentDistance = Double.parseDouble(distanceField.getText().trim());

            int points = calculatePoints(currentTravelType, currentDistance);
            double carbon = calculateCarbonReduction(currentTravelType, currentDistance);

            pointsPreviewLabel.setText("预计获得积分: " + points);
            carbonPreviewLabel.setText("预计碳减排: " + String.format("%.2f", carbon) + " kg");
        };

        // 为出行方式添加监听器
        travelTypeComboBox.addActionListener(previewCalculator);

        // 初始计算一次预览
        previewCalculator.actionPerformed(null);

        contentPanel.add(formPanel, BorderLayout.CENTER);

        // 创建按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton cancelButton = new JButton("取消");
        cancelButton.addActionListener(e -> dialog.dispose());

        JButton saveButton = new JButton("保存记录");
        saveButton.setBackground(new Color(0, 120, 0));
        saveButton.setForeground(Color.WHITE);
        saveButton.addActionListener(e -> {
            // 验证和保存记录
            String selectedTravelType = (String) travelTypeComboBox.getSelectedItem();
            String startLoc = startLocationField.getText().trim();
            String endLoc = endLocationField.getText().trim();
            String distanceStr = distanceField.getText().trim();
            Date selectedDate = (Date) dateSpinner.getValue();

            // 创建并保存出行记录
            TravelRecord record = new TravelRecord(
                    currentUser.getId(),
                    selectedDate,
                    selectedTravelType,
                    startLoc,
                    endLoc,
                    Double.parseDouble(distanceStr));

            TravelRecordDAO recordDAO = new TravelRecordDAO();
            int points = calculatePoints(selectedTravelType, Double.parseDouble(distanceStr));
            double carbon = calculateCarbonReduction(selectedTravelType, Double.parseDouble(distanceStr));
            record.setEarnedPoints(points);
            record.setCarbonReduction(carbon);

            boolean success = recordDAO.addTravelRecord(record);

            if (success) {
                JOptionPane.showMessageDialog(dialog,
                        "记录添加成功！\n获得积分: " + points + "\n减少碳排放: " + String.format("%.2f", carbon) + " kg",
                        "成功",
                        JOptionPane.INFORMATION_MESSAGE);
                dialog.dispose();
            } else {
                JOptionPane.showMessageDialog(dialog, "记录添加失败，请稍后再试！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        buttonPanel.add(cancelButton);
        buttonPanel.add(saveButton);
        contentPanel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.setContentPane(contentPanel);
        dialog.setVisible(true);
    }

    /**
     * 计算积分
     */
    private int calculatePoints(String travelType, double distance) {
        int points = 0;

        switch (travelType) {
            case "公交":
                points = (int) (distance * 2);
                break;
            case "地铁":
                points = (int) (distance * 1.5);
                break;
            case "共享单车":
                points = (int) (distance * 3);
                break;
            case "自行车":
                points = (int) (distance * 4);
                break;
            case "步行":
                points = (int) (distance * 5);
                break;
        }

        return Math.max(points, 1); // 至少1积分
    }

    /**
     * 计算碳减排量
     */
    private double calculateCarbonReduction(String travelType, double distance) {
        double carbonReduction = 0;

        switch (travelType) {
            case "公交":
                carbonReduction = distance * 0.1; // 每公里减少0.1kg碳排放
                break;
            case "地铁":
                carbonReduction = distance * 0.08; // 每公里减少0.08kg碳排放
                break;
            case "共享单车":
                carbonReduction = distance * 0.22; // 每公里减少0.22kg碳排放
                break;
            case "自行车":
                carbonReduction = distance * 0.25; // 每公里减少0.25kg碳排放
                break;
            case "步行":
                carbonReduction = distance * 0.27; // 每公里减少0.27kg碳排放
                break;
        }

        return carbonReduction;
    }

    /**
     * 重置到搜索状态
     */
    private void resetToSearchState() {
        // 获取搜索面板（即左侧面板）
        JPanel searchPanel = (JPanel) ((BorderLayout) getLayout()).getLayoutComponent(BorderLayout.CENTER);
        JPanel leftPanel = (JPanel) ((BorderLayout) searchPanel.getLayout()).getLayoutComponent(BorderLayout.WEST);

        // 移除路线结果面板（如果存在）
        Component[] components = leftPanel.getComponents();
        for (int i = 0; i < components.length; i++) {
            if (components[i] instanceof JPanel && components[i].getName() != null
                    && components[i].getName().equals("routeResultPanel")) {
                leftPanel.remove(components[i]);
                break;
            }
        }

        // 清除路线和起终点
        currentRoute.clear();
        currentTransportType = null;

        // 刷新界面
        leftPanel.revalidate();
        leftPanel.repaint();

        // 清除原有的下方结果面板（以防万一）
        resultPanel.removeAll();
        resultPanel.revalidate();
        resultPanel.repaint();

        // 刷新地图显示
        mapTable.repaint();
    }
}